package it.scambiocorse.utils;

import java.lang.reflect.Method;
import java.sql.*;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ResourceManager
{

 public ResourceManager()
 {
 }

 public static DataSource getDataSource()
 {
     if(dataSource == null)
         dataSource = (DataSource)ctx.getBean("dataSource");
     return dataSource;
 }

 public static Object getBean(String name)
 {
     return ctx.getBean(name);
 }

 public static void chiudiConnessione(Connection conn, Statement stmt, ResultSet rs)
 {
     if(rs != null)
         try
         {
             rs.close();
         }
         catch(Exception e) { }
     if(stmt != null)
         try
         {
             stmt.close();
         }
         catch(Exception e) { }
     if(conn != null)
         try
         {
             conn.setAutoCommit(true);
             conn.close();
         }
         catch(Exception e) { }
 }

 public static void releaseObject(Object obj)
 {
     if(obj != null)
         try
         {
             Class dbObj = obj.getClass();
             Method closeObj = dbObj.getMethod("close", new Class[0]);
             closeObj.invoke(obj, (Object[])null);
         }
         catch(Exception exception) { }
 }

 private static DataSource dataSource = null;
 private static ApplicationContext ctx = null;

 static 
 {
     ctx = new ClassPathXmlApplicationContext("classpath:resource.xml");
 }
}